package com.liu.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Component
@Slf4j
public class AliOSSUtils {
    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    private String accessKeyId = "LTAI5tDDbvtRb2kEHe29tLDK";
    private String accessKeySecret = "eQi0OlyG2Kk3Zvz8q5wgxJmKdvmHK0";
    private String bucketImg = "img-liuhaha";
    private String bucketVideo = "video-liuhaha";


    /**
     * 实现上传图片到OSS
     * mod，0是图片，1是视频
     */
    public String upload(MultipartFile file,int mod) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String url = null;
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();
        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        if(mod == 0){
            //上传文件到 OSS
            ossClient.putObject(bucketImg, fileName, inputStream);
            //文件访问路径
            url = endpoint.split("//")[0] + "//" + bucketImg + "." + endpoint.split("//")[1] + "/" + fileName;
        }else {
            ossClient.putObject(bucketVideo, fileName, inputStream);
            url = endpoint.split("//")[0] + "//" + bucketVideo + "." + endpoint.split("//")[1] + "/" + fileName;
        }
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

    public void delete(String img,String video) throws Exception{
        //Object完整路径中不能包含Bucket名称。
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
            // 删除文件。
            ossClient.deleteObject(bucketImg, img);
            ossClient.deleteObject(bucketVideo,video);
            log.info("删除成功");
            ossClient.shutdown();
        }


}
